import React, { useEffect, useState, useRef, createElement } from 'react'
import { List, Avatar, Image, message, Button, Modal, Input, Space, Drawer, Cascader, Tooltip, Row, Col, Popconfirm } from 'antd';
import { PlusSquareTwoTone, HeartTwoTone } from '@ant-design/icons';
import axios from 'axios';
import GoodsCascader from '../../../../components/GoodsCascader'
import moment from 'moment'
import { useNavigate } from 'react-router-dom'
import myprovinceData from '../../../../js/provinceData';
const { Search } = Input;
export default function Index() {
  const loginUser = JSON.parse(localStorage.getItem("loginUser"));
  let changeInfo = { title: '', message: '', mytype: '', wanttype: '', createrid: JSON.parse(localStorage.getItem("loginUser")).id };
  let changeapply = {}
  const navigate = useNavigate()
  const [listData, setListData] = useState([]);
  const [listDataBac, setListDataBac] = useState([]); //存一份获取的数据用于筛选
  const [mylistData, setmyListData] = useState([]);
  const [visible, setVisible] = useState(false);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [respondentchangeinfoid, setRespondentchangeinfoid] = useState(false);
  const titleRef = useRef()
  const messageRef = useRef()
  useEffect(() => {
    axios.get("http://localhost:8080/qryAllChangeXme?id=" + loginUser.id).then(resp => {

      setListData(resp.data.data);
      setListDataBac(resp.data.data)

    })
    return () => {
    };
  }, []);

  const openDrawer = (id) => {
    //id =>被申请交换的chaninfo id
    console.log('被申请交换的chaninfo id是:', id)
    setRespondentchangeinfoid(id)
    axios.get("http://localhost:8080/qryMyChange?id=" + loginUser.id).then(resp => {
      if (resp.data.state === "0") {
        setmyListData(resp.data.data);
      }
    })
    setDrawerVisible(true)

  }
  //创建交换 打开modal显示
  const makeChange = () => {
    setVisible(true);

  }
  //创建交换的modal 确定后
  const handleOk = () => {
    message.destroy();
    changeInfo.title = titleRef.current.state.value;
    changeInfo.message = messageRef.current.resizableTextArea.textArea.value;
    console.log("新增交换信息:", changeInfo);

    if (changeInfo.title == '' || changeInfo.message == '' || changeInfo.mytype == '' || changeInfo.wanttype == '') {
      message.error("请填写完交换信息!")
      setTimeout(() => {
        window.location.reload()
      }, 200);

    } else {
      axios.post('http://localhost:8080/makeChange', changeInfo).then(resp => {
        if (resp.data.state === "0") {
          message.success(resp.data.message, 1);
          setTimeout(() => {
            window.location.reload()
          }, 200);
        } else {
          message.error("网络异常!", 1);
        }
      })
    }
  }

  //创建交换modal 取消
  const handleCancel = () => {
    setVisible(false)
  }

  const mytypeChange = (value) => {
    let lastIndex = value.length - 1
    let rs = value[lastIndex]
    console.log(rs);
    changeInfo.mytype = rs;
  }

  const wanttypeChange = (value) => {
    let lastIndex = value.length - 1
    let rs = value[lastIndex]
    console.log(rs);
    changeInfo.wanttype = rs;
  }
  const drawerClose = () => {
    setDrawerVisible(false)
  }
  const makeApplyChange = (id) => {
    console.log('选择的我的交换id是:', id)
    changeapply.applychangeinfoid = id; //交换发起changoinfo id
    changeapply.applyerid = loginUser.id;
    changeapply.respondentchangeinfoid = respondentchangeinfoid
    axios.post("http://localhost:8080/makeApplyChange", changeapply).then(resp => {
      if (resp.data.state === "0") {
        message.success("请求成功,等待对方回应!", 1);
        setTimeout(() => {
          window.location.reload();
        }, 800);
      } else {
        message.error("操作失败!", 1)
        setTimeout(() => {
          window.location.reload();
        }, 800);
      }
    }).catch(err => {
      message.error("网络异常", 1);
    })
  }
  const filterByGoods = (value) => {
    console.log(value);
    if (value) { //如果筛选了 执行
      let lastIndex = value.length - 1
      console.log("baclistdata", listDataBac);
      setListData(listDataBac)
      let rs = value[lastIndex]
      console.log("筛选物品:", value);
      console.log("最终筛选物品str", rs);
      const newListData = listDataBac.filter(item => item.mytype === rs)
      console.log("物品类别筛选后的结果:", newListData);
      setListData(newListData)
    } else { //点击X后就是undefined把备份的listdata赋回去
      setListData(listDataBac)
    }

  }
  const filterCity = (value) => {
    console.log(value);
    if (value) { //如果筛选了 执行
      console.log("baclistdata", listDataBac);
      setListData(listDataBac)
      let rs = "";
      for (let i = 0; i < value.length; i++) {
        rs += value[i];
      }
      console.log("筛选物品:", value);
      console.log("最终筛选物品str", rs);
      const newListData = listDataBac.filter(item => item.city === rs)
      console.log("物品类别筛选后的结果:", newListData);
      setListData(newListData)
    } else { //点击X后就是undefined把备份的listdata赋回去
      setListData(listDataBac)
    }
  }

  const toggleLike = (item) => {
    console.log(item);
    item.like == 1 ? item.like = 0 : item.like = 1;
    console.log("切换后", item);
    let params = {}
    params.userid = loginUser.id
    params.changeinfoid = item.id
    params.like = item.like
    axios.post("http://localhost:8080/saveLike", params).then(
      setTimeout(() => {
        window.location.reload()
      }, 100)
    )

  }
  const searchGoods = (value) => {
    console.log(value);
    if (value != '') {
      const newListData = listDataBac.filter(item => item.title.indexOf(value) != -1 || item.message.indexOf(value) != -1)
      setListData(newListData)
    } else {
      console.log("reset");
      setListData(listDataBac)
    }
  }
  return (
    <div className="animate__animated animate__fadeIn">
      <Row justify="start">
        <Col xs={12} sm={8} md={5} xl={3}> <Search placeholder="搜索" onSearch={searchGoods} allowClear style={{ width: '1REM', }} /></Col>
        <Col xs={12} sm={8} md={5} xl={3}> <GoodsCascader onChange={filterByGoods} title="物品类别筛选" style={{ width: '1REM', }} /></Col>
        <Col xs={12} sm={8} md={5} xl={3}> <Cascader placeholder={"城市"} onChange={filterCity} style={{ width: '1REM', }} options={myprovinceData} defaultValue={''} /></Col>
      </Row>
      <List
        itemLayout="vertical"
        size="large"
        pagination={{
          onChange: page => {
            console.log(page);
          },
          pageSize: 3,
        }}
        dataSource={listData}

        renderItem={item => (
          <List.Item
            key={item.id}
            actions={[
              <Button type="primary" onClick={() => { openDrawer(item.id) }}> 申请交换</Button>,
              <Popconfirm
                title={item.like > 0 ? "取消收藏?" : "收藏此物品?"}
                onConfirm={() => { toggleLike(item) }}
                okText="是"
                cancelText="否"
              >
                <Space style={{ cursor: 'pointer' }}> <HeartTwoTone twoToneColor={item.like > 0 ? "#eb2f96" : ""} />{item.like > 0 ? "已收藏" : ""}</Space>
              </Popconfirm>
            ]}
            extra={
              <Image
                width={135}
                height={135}
                src={`http://localhost:8080/getChangeInfoPhoto?id=${item.id}`}
                fallback=""
              />
            }
          >
            <List.Item.Meta
              avatar={<Avatar src={`http://localhost:8080/getUserHead?id=${item.createrid}`} />}//头像
              title={`${item.title}`}
              description={moment(Number(item.createtime)).format('YYYY-MM-DD HH:mm:ss')}
            />
            {item.message}

          </List.Item>
        )}

      />
      <div style={{ position: 'fixed', right: '0.3REM', bottom: '0.3REM' }}>
        <Button onClick={makeChange} icon={<PlusSquareTwoTone width={100} />} style={{ width: 100, height: 40 }} type={'primary'}>创建</Button>
      </div>
      <Modal
        title="创建交换"
        visible={visible}
        onOk={handleOk}
        onCancel={handleCancel}
        // width={'30%'}
        centered={true}
      >
        <Row justify="center">
          <Col>
            <GoodsCascader style={{ width: '1.7REM', marginTop: '0.03REM' }} title="我的旧物类别" onChange={mytypeChange} />
          </Col>
        </Row>
        <Row justify="center">
          <Col>
            <GoodsCascader title="想要的类别" style={{ width: '1.7REM', marginTop: '0.03REM' }} onChange={wanttypeChange} />
          </Col>
        </Row>
        <Row justify="center">
          <Col>
            <Input placeholder="创建标题" style={{ width: '1.7REM', marginTop: '0.03REM' }} ref={titleRef}></Input>
          </Col>
        </Row>
        <Row justify="center">
          <Col>
            <Input.TextArea placeholder="具体描述" style={{ width: '1.7REM', marginTop: '0.03REM' }} ref={messageRef} />
          </Col>
        </Row>
      </Modal>

      <Drawer
        title="选择你的物品用以交换"
        placement='bottom'
        width={500}
        onClose={drawerClose}
        height={'80%'}
        visible={drawerVisible}
      >
        <List
          itemLayout="vertical"
          size="large"
          pagination={{
            onChange: page => {
              console.log(page);
            },
            pageSize: 3,
          }}
          dataSource={mylistData}

          renderItem={item => (
            <List.Item
              key={item.id}
              extra={
                <Image
                  width={135}
                  height={135}
                  src={`http://localhost:8080/getChangeInfoPhoto?id=${item.id}`}
                />
              }
            >
              <List.Item.Meta
                avatar={<Avatar src={`http://localhost:8080/getUserHead?id=${item.createrid}`} />}
                title={loginUser.title}
                description={`标题:${item.title}`}
              />
              {item.message} <br />
              <Button type='primary' style={{ marginTop: 20 }} onClick={() => { makeApplyChange(item.id) }}>选择</Button>

            </List.Item>
          )}

        />
      </Drawer>

    </div>
  )
}
